//
//  UIAlertControllerExtension.swift
//  zhende
//
//  Created by 陆文宇 on 2017/5/26.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import UIKit

var alertControllers: [UIAlertController] = []

extension UIAlertController {
    
    static func yy_showAlert(title: String?, message: String? = nil, confirmTitle: String = "知道了") {
        let alertC = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertC.addAction(UIAlertAction(title: confirmTitle, style: .cancel, handler: { (_) in
            if alertControllers.isEmpty {
                return
            }
            
            alertControllers.removeFirst()
            if let first = alertControllers.first {
                YYRouter.currentVC.present(first, animated: true, completion: nil)
            }
        }))
        
        if alertControllers.isEmpty {
            YYRouter.currentVC.present(alertC, animated: true, completion: nil)
        }
        alertControllers.append(alertC)
    }
    
    static func yy_showAlert(title: String?, message: String?, confirmTitle: String = "确定", confirmAction: @escaping () -> Void) {
        let alertC = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let cancel = {
            if alertControllers.isEmpty {
                return
            }
            
            alertControllers.removeFirst()
            if let first = alertControllers.first {
                YYRouter.currentVC.present(first, animated: true, completion: nil)
            }
        }
        alertC.addAction(UIAlertAction(title: confirmTitle, style: .destructive, handler: { (_) in
            confirmAction()
            cancel()
        }))
        alertC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            cancel()
        }))
        
        if alertControllers.isEmpty {
            YYRouter.currentVC.present(alertC, animated: true, completion: nil)
        }
        alertControllers.append(alertC)
    }
}
